<?php

namespace app\api\model\gifts;

use app\common\model\gifts\UserGifts as UserGiftsModel;

/**
 * 用户爆品礼模型
 * Class UserGifts
 * @package app\api\model
 */
class UserGifts extends UserGiftsModel
{

    /**
     * 获取用户购买的爆品礼列表
     * @param $user_id
     * @param bool $is_use 是否已使用
     * @param bool $is_expire 是否已过期
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyLists($param,$user_id)
    {
        $page = isset($param['page']) && is_numeric($param['page']) ? intval($param['page']) : 1;
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $list = $this->with(['image'])
            ->where(['user_id'=>$user_id,'is_delete'=>0,'type'=>0])
            ->field([
                    'user_gifts_id, 
                    user_id,
                    gifts_id,
                    gifts_title,
                    image_id,
                    gifts_line_price,
                    gifts_price,
                    gifts_discription,
                    start_time,
                    end_time, 
                    is_expire,
                    write_status'
            ])
            ->order(['create_time' => 'desc'])
            ->limit($offset, $limit)
            ->select();
        return $list;
    }


    /**
     * 获取用户购买的爆品礼列表
     * @param $user_id
     * @param bool $is_use 是否已使用
     * @param bool $is_expire 是否已过期
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function receiveLists($param,$user_id)
    {
        $page = isset($param['page']) && is_numeric($param['page']) ? intval($param['page']) : 1;
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $list = $this->with(['image'])
            ->where(['user_id'=>$user_id,'is_delete'=>0,'type'=>1])
            ->field([
                   'user_gifts_id, 
                    user_id,
                    gifts_id,
                    gifts_title,
                    image_id,
                    gifts_line_price,
                    gifts_price,
                    gifts_discription,
                    start_time,
                    end_time, 
                    is_expire'
            ])
            ->order(['create_time' => 'desc'])
            ->limit($offset, $limit)
            ->select();
        return $list;
    }


    /**
     * 获取用户已经购买的爆品礼ID集
     * @param $user_id
     * @return array
     */
    public function getBuyGiftsIds($user_id)
    {
        return $this->where(['user_id'=>$user_id,'type'=>0,'is_expire'=>0])->column('gifts_id');
    }

    /**
     * 获取微股客已经领取爆品礼ID集
     * @param $user_id
     * @return array
     */
    public function getKeGiftsIds($user_id)
    {
        return $this->where(['user_id'=>$user_id,'type'=>1,'is_expire'=>0])->column('gifts_id');
    }


    /**
     * 领取爆品礼
     * @param $user
     * @param $gifts
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public function receive($user, $gifts_id,$superior_user_id)
    {
        // 获取爆品礼信息
        $gifts = Gifts::detail($gifts_id);
        // 验证爆品礼是否可领取
        if (!$this->checkReceive($user, $gifts)) {
            return false;
        }
        // 添加领取记录
        return $this->add($user, $gifts,$superior_user_id);

    }


    /**
     * 添加领取记录
     * @param $user
     * @param gifts $gifts
     * @return bool
     */
    private function add($user,$gifts,$superior_user_id)
    {
        if($user['user_id']==$superior_user_id){
            $superior_user_id = 0;
        }

        // 整理领取记录
        $data = [
            'superior_user_id' => $superior_user_id,//推荐人id
            'user_id' => $user['user_id'],//用户id
            'gifts_id' => $gifts['gifts_id'],//爆品礼id
            'gifts_title' => $gifts['gifts_title'],//爆品礼id
            'gifts_type' => $gifts['gifts_type'],//爆品礼包类型(10免费 20不免费)
            'image_id' => $gifts['image_id'],//爆品礼包图片
            'gifts_line_price' => $gifts['gifts_line_price'],//爆品礼划线价
            'gifts_price' => $gifts['gifts_price'],//现价
            'gifts_distribution_price' => $gifts['gifts_distribution_price'],//爆品礼物分销价格
            'gifts_discription' => $gifts['gifts_discription'],//爆品简介
            'start_time' => $gifts['start_time']['value'],//固定时间-开始时间
            'end_time' => $gifts['end_time']['value'],//固定时间-结束时间
            'wxapp_id' => self::$wxapp_id,
            'type' => 1,
        ];

        return $this->transaction(function () use ($data, $gifts) {
            // 添加领取记录
            $status = $this->save($data);
            if ($status) {
                // 更新优惠券领取数量
                $gifts->setIncReceiveNum();
            }
            return $status;
        });
    }



    /**
     * 购买增加记录
     * @param $data
     */
    public function addPayLog($data)
    {
        db('gifts')->where(['gifts_id'=>$data['gifts_id']])->setInc('receive_num');
        db('gifts')->where(['gifts_id'=>$data['gifts_id']])->setDec('gifts_stock_num');
        $this->save($data);
    }


    /**
     * 购买爆品礼
     * @param $user
     * @param $gifts_id
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public function checkBuy($user, $gifts_id)
    {
        // 获取爆品礼信息
        $gifts = Gifts::detail($gifts_id);
        // 验证爆品礼是否可领取
        if (!$this->checkCanBuy($user, $gifts)) {
            return false;
        }
        return true;

    }


    /**
     * 验证爆品礼是否可购买
     * @param $user
     * @param Gifts $gifts
     * @return bool
     */
    private function checkCanBuy($user, $gifts)
    {
        if (!$gifts) {
            $this->error = '爆品礼不存在';
            return false;
        }
        if (!$gifts->checkCanBuy()) {
            $this->error = $gifts->getError();
            return false;
        }

        // 验证是否已购买
        $userGiftsIds = $this->getBuyGiftsIds($user['user_id']);
        if (in_array($gifts['gifts_id'], $userGiftsIds)) {
            $this->error = '该爆品礼已购买';
            return false;
        }
        return true;
    }



    /**
     * 购买爆品礼
     * @param $user
     * @param Gifts $gifts
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public function checkReceive($user, $gifts)
    {
        if (!$gifts) {
            $this->error = '爆品礼不存在';
            return false;
        }
        if (!$gifts->checkReceive()) {
            $this->error = $gifts->getError();
            return false;
        }

        // 验证是否已购买
        $userGiftsIds = $this->getKeGiftsIds($user['user_id']);
        if (in_array($gifts['gifts_id'], $userGiftsIds)) {
            $this->error = '该爆品礼已领取';
            return false;
        }
        return true;

    }


    /**
     * 已经领取的爆品礼详情
     * @param $userGiftsId
     * @return static
     */
    public static function isGetDetail($userGiftsId)
    {
        /* @var $model self */
        $model = (new static)->with([
            'image',
        ])->where(['user_gifts_id'=>$userGiftsId,'is_delete'=>0,'type'=>1])
            ->find();

        if (empty($model)) {
            return $model;
        }
        // 整理商品数据并返回
        return $model;
    }


    /**
     * 已经领取的爆品礼详情
     * @param $userGiftsId
     * @return static
     */
    public static function buyGetDetail($userGiftsId)
    {
        /* @var $model self */
        $model = (new static)->with([
            'image',
        ])->where(['user_gifts_id'=>$userGiftsId,'is_delete'=>0,'type'=>0])
            ->find();
        if($model){
            $qr_url = \base_url().'QR/QR.php?url=';
            $model['qrimg'] =  $qr_url.$model['order_id'];
        }

        // 整理商品数据并返回
        return $model;
    }



}
